import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:hktk_app/dao/industry_dao.dart';
import 'package:hktk_app/dao/subject_dao.dart';
import 'package:hktk_app/exception/dao_exception.dart';
import 'package:hktk_app/model/data_model.dart';
import 'package:hktk_app/model/home/exam_key_model.dart';
import 'package:hktk_app/model/subject/records_model.dart';
import 'package:hktk_app/pages/question/random_question_page.dart';
import 'package:hktk_app/pages/subject/child/paper_detail_widget.dart';
import 'package:hktk_app/util/data_util.dart';
import 'package:hktk_app/util/font_util.dart';
import 'package:hktk_app/util/toast_util.dart';
import 'package:hktk_app/util/view_util.dart';
import 'package:hktk_app/widget/back_button_widget.dart';
import 'package:hktk_app/widget/subject/test_background_widget.dart';

/// 随机组卷页面
class TestPaperPage extends StatefulWidget {
  /// 标题
  final String title;

  /// 栏目id
  final String columnId;
  final int categoryId;

  const TestPaperPage({
    super.key,
    required this.title,
    required this.columnId,
    required this.categoryId,
  });

  @override
  State<TestPaperPage> createState() => _TestPaperPageState();
}

class _TestPaperPageState extends State<TestPaperPage> {
  late BuildContext _context;

  /// 初始化数据方法
  late Future<Map<String, dynamic>> _futureInit;

  /// 记录相关数据
  late RecordsModel? _recordsModel;

  @override
  void initState() {
    super.initState();

    _recordsModel = null;
    _futureInit = _initData();
  }

  @override
  Widget build(BuildContext context) {
    _context = context;
    // 获取安全边界
    return Scaffold(
      backgroundColor: colorWhite1,
      body: SafeArea(
        child: Column(
          children: [
            _titleItem(),
            Expanded(child: _futureItem()),
            // Padding(
            //   padding: EdgeInsets.symmetric(vertical: 40, horizontal: 16),
            //   child: SizedBox(
            //     height: 700,
            //     child: SingleChildScrollView(
            //       child: Card(
            //         elevation: 10,
            //         child: Container(
            //           height: 700,
            //           decoration: BoxDecoration(
            //             image: const DecorationImage(
            //               image: AssetImage("images/question/aaa.png"),
            //               // fit: BoxFit.fitHeight,
            //               fit: BoxFit.fill,
            //             ),
            //             borderRadius: BorderRadius.circular(10),
            //           ),
            //           child:  FutureBuilder<Map<String, dynamic>>(
            //             future: _futureInit,
            //             builder: (
            //                 BuildContext context,
            //                 AsyncSnapshot<Map<String, dynamic>> snapshot,
            //                 ){
            //               if (snapshot.connectionState == ConnectionState.done) {
            //                 Map<String, dynamic> map = snapshot.data!;
            //                 if (!map["suc"]) {
            //                   WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
            //                     ToastUtil.show(context: context, msg: map["msg"]);
            //                   });
            //                 }
            //                 return _content();
            //               } else {
            //                 return const Center(
            //                   child: CircularProgressIndicator(),
            //                 );
            //               }
            //             },
            //           ),
            //         ),
            //       ),
            //     ),
            //   ),
            // ),
          ],
        ),
      ),
    );
  }

  /// 初始化数据方法
  Future<Map<String, dynamic>> _initData() async {
    Map<String, dynamic> map = {};
    try {
      ExamKeyModel examKeyModel = IndustryDao.getExamKey();
      DataModel dataModel = dataUtilComm.dataModel;

      _recordsModel = await SubjectDao.generateRandomRecords(
        // industryCode: dataModel.industryId,
        // examId: dataModel.examId,
        // categoryId: dataModel.categoryId,
        // columnId: widget.columnId,
        industryCode: examKeyModel.industryId,
        examId: examKeyModel.examId,
        categoryId: widget.categoryId,
        columnId: widget.columnId,
      );

      map["suc"] = true;
    } catch (e) {
      map = {"suc": false, "msg": "未知错误，请重试"};
      if (e is DaoException) {
        map["msg"] = e.msg;
      }
    }
    return map;
  }

  /// 标题组件
  _titleItem() {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 44),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          // 占位使用
          SizedBox(
            width: 44,
            height: 44,
          ),
          Text(
            widget.title,
            style: FontUtil.fontBlack1(30, fontWeight: FontWeight.w500),
          ),
          BackButtonWidget.close(pageContext: _context),
        ],
      ),
    );
  }

  /// 加载数据组件
  _futureItem() {
    return FutureBuilder<Map<String, dynamic>>(
      future: _futureInit,
      builder: (
        BuildContext context,
        AsyncSnapshot<Map<String, dynamic>> snapshot,
      ) {
        if (snapshot.connectionState == ConnectionState.done) {
          Map<String, dynamic> map = snapshot.data!;
          if (!map["suc"]) {
            WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
              ToastUtil.show(context: context, msg: map["msg"]);
            });
          }
          return _content();
        } else {
          return const Center(
            child: CircularProgressIndicator(),
          );
        }
      },
    );
  }

  /// 内容显示组件
  _content() {
    return Column(
      children: [
        Expanded(child: _paperItem()),
        _bottomItem(),
      ],
    );
  }

  /// 底部按钮显示组件
  _bottomItem() {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 40),
      child: _buttonItem(),
    );
  }

  /// 按钮组件显示
  _buttonItem() {
    return GestureDetector(
      onTap: _onTapFunBtn,
      child: Container(
        // width: 318,
        // height: 40,
        padding: EdgeInsets.all(10),
        decoration: BoxDecoration(
          color: colorBlue1,
          borderRadius: BorderRadius.circular(44),
        ),
        child: Center(
          child: Text(
            "开始考试",
            style: FontUtil.fontWhile1(24, fontWeight: FontWeight.w500),
          ),
        ),
      ),
    );
  }

  /// 试卷组件显示
  _paperItem() {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 16),
      child: MediaQuery.removePadding(
        removeTop: true,
        context: _context,
        child: ListView(
          children: [
            hiSpace(height: 50),
            _paperConItem(),
            hiSpace(height: 48),
          ],
        ),
      ),
    );
  }

  /// 试卷内容显示
  _paperConItem() {
    return TestBackgroundWidget(
      widget: Padding(
        padding: EdgeInsets.only(top: 40, left: 30, right: 30),
        child: PaperDetailWidget.test(
          totalScore: _recordsModel?.allScore?.toInt(),
          scoreRight: _recordsModel?.passScore?.toInt(),
          qCount: _recordsModel?.qcount,
          remark: _recordsModel?.remark,
        ),
      ),
    );
  }

  /// 按钮点击方法
  void _onTapFunBtn() {
    if (_recordsModel == null) {
      ToastUtil.show(context: _context, msg: "记录创建失败，请退出重试！");
    } else {
      Navigator.pushNamed(context, "/random-question",
          arguments: {"recordsModel": _recordsModel!});
    }
  }
}
